package com.yc.framework.web.service;

import com.yc.common.constant.HttpStatus;
import com.yc.common.constant.PasswordConstants;
import com.yc.common.constant.Constants;
import com.yc.common.core.domain.model.LoginBody;
import com.yc.common.core.domain.model.LoginUser;
import com.yc.common.exceptions.ServiceException;
import com.yc.common.exceptions.user.UserDeleteException;
import com.yc.common.exceptions.user.UserDisabledException;
import com.yc.common.exceptions.user.UserPasswordNotMatchException;
import com.yc.common.utils.ip.IpUtil;
import com.yc.framework.manager.AsyncManager;
import com.yc.framework.manager.factory.AsyncFactory;
import com.yc.framework.security.context.AuthenticationContextHolder;
import com.yc.framework.web.domain.TokenInfo;
import com.yc.system.service.*;
import com.yc.common.core.domain.entity.SysUser;
import com.yc.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class SysLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 用户登录
     */
    public TokenInfo login(LoginBody loginUserDto) {

        // 获取登录信息
        String phone = loginUserDto.getPhone();
        String password = loginUserDto.getPassword();
        // 验证码信息
        String captchaId = loginUserDto.getCaptchaId();
        String userInputCode = loginUserDto.getCode();

        // 校验验证码前置检查
        loginPreCheck(phone, password);

        // 校验验证码
        captchaService.validateCaptcha(phone, captchaId, userInputCode);

        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(phone, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername，密码验证在那里完成
            authentication = authenticationManager.authenticate(authenticationToken);

            // 认证通过，保存认证信息到上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } catch (Exception e) {
            if (e instanceof UserPasswordNotMatchException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw e;
            }else if (e instanceof UserDisabledException || e instanceof UserDeleteException) {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw e;
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLoginInfo(phone, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }

        // 获取登录用户信息
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        SysUser user = loginUser.getUser();
        // 添加用户登录时间和ip地址
        recordLoginInfo(user.getId());

        // 生成Token
        TokenInfo tokenInfo = tokenService.createToken(loginUser);
        loginUser.setTokenInfo(tokenInfo);

        return tokenInfo;
    }

    /**
     * 登录前置校验
     *
     * @param phone    手机号
     * @param password 用户密码
     **/
    public void loginPreCheck(String phone, String password) {

        // 手机号或密码为空，错误
        if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(
                    phone, Constants.LOGIN_FAIL, "手机号或密码不能为空"));
            throw new ServiceException("手机号或密码不能为空", HttpStatus.BAD_REQUEST);
        }

        // 手机号格式校验出错
        if (phone != null && !phone.matches("^1[3-9]\\d{9}$")) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(
                    phone, Constants.LOGIN_FAIL, "手机号格式错误"));
            throw new ServiceException("手机号格式错误", HttpStatus.BAD_REQUEST);
        }

        // 密码长度不在范围内，错误
        if (password.length() < PasswordConstants.PASSWORD_MIN_LENGTH
                || password.length() > PasswordConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLoginInfo(
                    phone, Constants.LOGIN_FAIL, "密码长度限制为6-15位"));
            throw new ServiceException("密码长度限制为6-15位", HttpStatus.BAD_REQUEST);
        }
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    @Async
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setLastLoginIp(IpUtil.getLocalIpv4Address());
        sysUser.setLastLoginTime(new Date());
        sysUserService.updateUserProfile(sysUser);
    }
}